package com.hkjtgc.pcr_app.ui

import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.Fragment
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.navigation.NavigationView
import com.google.android.material.snackbar.Snackbar
import com.hkjtgc.pcr_app.R
import com.hkjtgc.pcr_app.database.DatabaseManager
import com.hkjtgc.pcr_app.fragment.*
import com.hkjtgc.pcr_app.model.TodoInfoDO
import com.hkjtgc.pcr_app.util.Constant
import com.hkjtgc.pcr_app.util.SharedPreferencesUtils
import com.hkjtgc.pcr_app.util.ToastUtil
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch


@Suppress("DEPRECATION")
@RequiresApi(Build.VERSION_CODES.M)
internal class MainActivity : AppCompatActivity(), View.OnClickListener {

    private lateinit var toolbar: Toolbar
    private lateinit var drawerLayout: DrawerLayout
    private lateinit var navigationView: NavigationView
    private lateinit var floatingActionButton: FloatingActionButton
    private lateinit var bottomNavigationView: BottomNavigationView

    private lateinit var currentFragment: Fragment
    private var homeFragment: Fragment = HomeFragment()
    private var careFragment: Fragment = CareFragment()
    private var helpFragment: Fragment = HelpFragment()
    private var shopFragment: Fragment = ShopFragment()
    private var testsFragment: Fragment = TestsFragment()

    private var name = SharedPreferencesUtils.getSPInstance(this).getSP(Constant.USER_NAME)

    private lateinit var institutionName: TextView
    private lateinit var contacts: TextView
    private lateinit var mobile: TextView
    private lateinit var address: TextView

    var list : List<TodoInfoDO>? = null
    @RequiresApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        setContentView(R.layout.activity_main)

        //测试往库里加数据
        GlobalScope.launch {
            try {
                DatabaseManager.saveApplication(application)
                //DatabaseManager.db.todoDao.insert(TodoInfoDO(operatorName = "测试", createDate = "2023-04-20 10:35:01", simpleType = "测试1", simpleName = "测试2", profileName = "ceshi3", profileSex = "nan", cardBoxName = "kahe", cardBoxType = "kahe", id = 1))
                list = DatabaseManager.db.todoDao().getAll()!!
            }catch (ex : Exception) {

            }
        }
        currentFragment = homeFragment //主页先显示出来
        init()
    }

    override fun onClick(view: View?) = when (view?.id) {
            R.id.float_button -> {
                Snackbar.make(view, "DATA deleted", Snackbar.LENGTH_LONG).setAction("Undo") {
                    ToastUtil.toastLong(this, "Data restored")
                }.show()
            }

            R.id.nav_material -> {

            }
        else -> {}
    }



    @SuppressLint("ResourceType")
    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.nav_right_menu, menu)
        return true
    }


    @SuppressLint("SetTextI18n")
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.navigation_bar_group -> {
                drawerLayout.openDrawer(GravityCompat.START)

                //初始化侧栏信息
                institutionName = findViewById(R.id.name)
                contacts = findViewById(R.id.contacts)
                mobile = findViewById(R.id.mobile)
                address = findViewById(R.id.address)

                institutionName.text = "名称:${SharedPreferencesUtils.getSPInstance(this).getSP(Constant.INSTITUTION_NAME)}"
                contacts.text = "负责人:${SharedPreferencesUtils.getSPInstance(this).getSP(Constant.INSTITUTION_CONTACTS)}"
                mobile.text = "负责人手机号:${SharedPreferencesUtils.getSPInstance(this).getSP(Constant.INSTITUTION_MOBILE)}"
                address.text = "地址:${SharedPreferencesUtils.getSPInstance(this).getSP(Constant.INSTITUTION_ADDRESS)}"
            }
        }
        return true
    }


    /**
     * 实现碎片的切换
     * @param fragment Fragment
     */
    private fun switchFragment(fragment: Fragment) {
        val transaction = supportFragmentManager.beginTransaction()
        if (!fragment.isAdded) {
            transaction.hide(currentFragment)
            transaction.add(R.id.main_fragment, fragment)
            transaction.show(fragment)
        } else {
            transaction.hide(currentFragment)
            transaction.show(fragment)
        }
        currentFragment = fragment
        transaction.commit()
    }


    @SuppressLint("UseCompatLoadingForDrawables", "CommitTransaction")
    private fun init() {
        title = "你好,${name}!"

        //主页面
        drawerLayout = findViewById(R.id.draw_layout)

        //浮动按钮
        floatingActionButton = findViewById(R.id.float_button)
        floatingActionButton.setOnClickListener(this)

        //顶部导航栏
        toolbar = findViewById(R.id.bar_main)
        this.setSupportActionBar(toolbar)

        //底部导航点击事件
        bottomNavigationOnClick()

        //溢出菜单点击事件
        navigationViewOnClick()

        if(SharedPreferencesUtils.getSPInstance(this).getSP(Constant.AUTO_ASSIGN) == ""){
            SharedPreferencesUtils.getSPInstance(this).putSP(Constant.AUTO_ASSIGN,"false")
        }


    }



    private fun bottomNavigationOnClick() {
        bottomNavigationView = findViewById(R.id.bottomNavigationView)
        bottomNavigationView.setOnNavigationItemSelectedListener {
            when (it.itemId) {
                R.id.menu_item_home -> {
                    //点击item换导航栏背景颜色
                    bottomNavigationView.itemBackground = getDrawable(R.color.blueGrey_500)
                    //切换碎片
                    switchFragment(homeFragment)
                    initHome()
                }
                R.id.menu_item_test -> {
                    bottomNavigationView.itemBackground = getDrawable(R.color.teal_500)
                    switchFragment(testsFragment)
                }
                R.id.menu_item_care -> {
                    bottomNavigationView.itemBackground = getDrawable(R.color.brown_500)
                    switchFragment(careFragment)
                }
                R.id.menu_item_help -> {
                    bottomNavigationView.itemBackground = getDrawable(R.color.grey_500)
                    switchFragment(helpFragment)
                }
                R.id.menu_item_shop -> {
                    bottomNavigationView.itemBackground = getDrawable(R.color.indigo_500)
                    switchFragment(shopFragment)
                }
                else -> switchFragment(homeFragment)
            }
            true
        }
        //显示主页面
        switchFragment(homeFragment)
    }


    private fun navigationViewOnClick() {
        //溢出菜单栏
        navigationView = findViewById(R.id.nav_material)
        navigationView.setNavigationItemSelectedListener {
            when (it.itemId) {
                R.id.item_people -> {
                    if(SharedPreferencesUtils.getSPInstance(this).getSP(Constant.AUTO_ASSIGN) == "false"){
                        it.setIcon(R.mipmap.iv_open)
                        ToastUtil.toastShort(this,"智能推荐已开启！")
                        SharedPreferencesUtils.getSPInstance(this).putSP(Constant.AUTO_ASSIGN,"true")
                    }else if(SharedPreferencesUtils.getSPInstance(this).getSP(Constant.AUTO_ASSIGN) == "true"){
                        it.setIcon(R.mipmap.iv_close)
                        ToastUtil.toastShort(this,"智能推荐已关闭！")
                        SharedPreferencesUtils.getSPInstance(this).putSP(Constant.AUTO_ASSIGN,"false")
                    }

                }

                R.id.item_setting -> {

                }

            }
            true
        }
    }


    private fun initHome(){
        //TODO 后续根据用户姓名，更新title
        title = "你好,${name}!"
    }

    override fun onResume() {
        super.onResume()
        GlobalScope.launch {
            try {
                DatabaseManager.saveApplication(application)
                list = DatabaseManager.db.todoDao().getAll()!!
            }catch (ex : Exception) {

            }
        }
    }
}